import React, { Component } from 'react'
import CommentInput from './CommentInput'
import CommentList from './CommentList'

class CommentApp extends Component {
  state = {}

  constructor() {
    super()
    this.state = {
      comments: [
        { username: 'Jerry', content: 'Hello', createdTime: 1535013243567 },
        { username: 'Tomy', content: 'World', createdTime: 1535013243567 },
        { username: 'Lucy', content: 'Good', createdTime: 1535013243567 }
      ]
    }
  }

  componentWillMount() {
    this._loadComments()
  }

  _loadComments() {
    let comments = localStorage.getItem('comments')
    if (comments) {
      comments = JSON.parse(comments)
      this.setState({ comments })
    }
  }
  _saveComments(comments) {
    localStorage.setItem('comments', JSON.stringify(comments))
  }

  handleDeleteComment(index) {
    console.log(index)
    const comments = [...this.state.comments]
    comments.splice(index, 1)
    this.setState({ comments })
    this._saveComments(comments)
  }

  handleSubmitComment(comment) {
    if (!comment) return
    if (!comment.username) return alert('请输入用户名')
    if (!comment.content) return alert('请输入评论内容')
    console.log(comment)
    // 不建议直接修改原数组，而是采用拷贝的形式，进行修改
    // this.state.comments.push(comment)
    const comments = [...this.state.comments]
    comments.push(comment)
    this.setState({ comments })
    this._saveComments(comments)
  }
  render() {
    return (
      <div className="wrapper">
        <CommentInput onSubmit={this.handleSubmitComment.bind(this)} />
        <CommentList
          comments={this.state.comments}
          onDeleteComment={this.handleDeleteComment.bind(this)}
        />
      </div>
    )
  }
}

export default CommentApp
